package com.ydj.app.config.resolver;

import com.ydj.framework.exception.VerifyTokenException;
import com.ydj.framework.resolver.BaseArgumentResolver;
import com.ydj.app.CmsConst;
import com.ydj.app.entity.CmsAccount;
import com.ydj.app.entity.dao.CmsAccountDao;
import com.ydj.app.protocol.redis.RdsCmsLoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * CMS参数转换器
 */
@Configuration
public class CmsArgumentResolver extends BaseArgumentResolver<RdsCmsLoginInfo> {
    @Autowired
    private CmsAccountDao userDao;

    @Autowired
    private CmsConst cmsConst;

    @Override
    public String prePath() {
        return cmsConst.getBaseUrl() + "/";
    }

    @Override
    protected void createArgFormat(List<ArgFormat> list) {
        list.add(new ArgFormat("accountId", Long.class));
        list.add(new ArgFormat("account", CmsAccount.class));
    }

    @Override
    protected Object doResolveArgument(String parameterName, RdsCmsLoginInfo info) throws VerifyTokenException {
        switch (parameterName) {
            case "accountId":
                return getAccountId(info);
            case "account":
               return getAccount(info);
            default:
                break;
        }
        return null;
    }

    private Long getAccountId(RdsCmsLoginInfo info) throws VerifyTokenException {
        Long accountId = info.getAccountId();
        if (accountId == null) {
            throw new VerifyTokenException();
        }
        return accountId;
    }

    private CmsAccount getAccount(RdsCmsLoginInfo info) throws VerifyTokenException {
        Long userId = getAccountId(info);
        CmsAccount user = userDao.getById(userId);
        if (user == null) {
            throw new VerifyTokenException();
        }
        return user;
    }
}